/**
 * 数据上报统计
 */
import http from "@/utils/http";

// const SAVE_URL = `http://192.168.11.29:8080/yncjcms_client/client/insertUserBeInfo.htm`;
import {getUrlParams} from "./uitils";
const { version } = getUrlParams();

import localforage from "localforage";
const db = localforage.createInstance({
  name: "yn-client-report",
});

const DBKEY = "playing-video";
const matchToken = window.location.href.match(/token=([^&]+)/);

// 定时更新结束时间
setInterval(async function() {
  updateLocalData({ endTime: Date.now() });
}, 1000);

/**
 * 上报数据(播放URL变更时触发)
 * @param {Object} data - 上报需要的数据
 * @param {String} data.playUrl - 播放地址
 * @param {String} data.videoName - 视频名称
 * @param {String} data.planTime - 视频的计划开始时间
 */
export default async function reportSubmit(playUrl) {
  const token = matchToken ? matchToken[1] : "";
  if (process.env.NODE_ENV == "production" && !token) {
    return;
  }

  // 上报上次数据
  const localData = await db.getItem(DBKEY);
  if (localData && localData.playUrl) {
    const json = createSchema(localData);
    console.log("上报数据", json);
    const data = JSON.stringify(json);
    const params = {
      data: data,
    };
    const SAVE_URL = "/client/insertUserBeInfoDate.htm";
    await http.post(SAVE_URL, params);
    await db.clear();
  }
  updateLocalData({
    playUrl,
    ...window.reportParams,
    startTime: Date.now(),
    token,
  });
}

/**
 * 更新缓存数据
 */
async function updateLocalData(data) {
  const cache = await db.getItem(DBKEY);
  db.setItem(DBKEY, { ...cache, ...data });
}

function createSchema(data) {
  const {
    token,
    endTime,
    startTime,
    playUrl,
    videoName,
    planTime,
    cateId,
    id,
  } = data;
  
  const isLive = /gensee/.test(playUrl);
  const liveType = isLive ? 0 : 1;
  const liveTypeText = isLive ? "直播" : "录播";
  const eventCode = isLive ? "00006" : "00007";
  const duration = endTime - startTime;

  return {
    user: {
      token,
      // checkCode: Number(version),
      checkCode: Number(version)==1000?8:Number(version),
    },
    module: {
      project: "YNGP_PC",
      moduleCode: "0003",
    },
    event: [
      {
        eventCode: eventCode,
        eventLevel: 1,
        eventDescription: liveTypeText,
        eventSubject: {
          recordId: id,
          objectkey: cateId,
          starttime: startTime,
          endtime: endTime,
          duration: duration,
          objectValue: videoName,
          extend: {
            videoType: liveType,
            programSchedule: planTime,
          },
        },
      },
    ],
  };
}
